# -*- coding:utf-8 -*-

class Pagination:
	def __init__(self, current_page, all_num, show_num=10):
		"""
		分页模块
		:param current_page: 当前页
		:param all_num: 所有数据的条数
		:param show_num: 每页显示数据的条数
		"""
		# 当前页  --当current_page转换出错或小于1时，将其置为1
		try:
			current_page = int(current_page)
		except:
			current_page = 1
		if current_page < 1:
			current_page = 1
		self.current_page = current_page

		# 内容的显示数量(默认为10)  --当show_num转换出错或小于1时，将其置为默认10
		try:
			show_num = int(show_num)
		except:
			show_num = 10
		if show_num < 1:
			show_num = 10
		self.show_num = show_num

		# 总页数  --当`(总数量/显示数量)`的余数大于0时，则总页数加1
		all_page, c = divmod(all_num, self.show_num)  # divmod(a,b)  --实现a除以b，然后返回商与余数的元组
		if c > 0:
			all_page += 1
		self.all_page = all_page

	@property   # property装饰器函数把 get/set 方法“装饰”成属性调用，即调用该方法就不用在方法名后加`()`了
	def start(self):
		return (self.current_page-1) * self.show_num

	@property
	def end(self):
		return self.current_page * self.show_num

	def page_num(self,base_url):
		# bf--before, af--after
		page_list = []
		if self.all_page < 11:
			bf = 1
			af = self.all_page
		else:
			if self.current_page <= 6:
				bf = 1
				af = 11
			else:
				if (self.current_page + 5) > self.all_page:
					bf = self.all_page - 10
					af = self.all_page
				else:
					bf = self.current_page - 5
					af = self.current_page + 5

		# 首页
		first_page = '<a href="{}{}">首页</a>'.format(base_url, 1)
		page_list.append(first_page)

		# 上一页  --即当前页减1（注意当前页为1时，需判断）
		if self.current_page == 1:
			prev_page = '<a href="javascript:void(0);">上一页</a>'
		else:
			prev_page = '<a href="{}{}">上一页</a>'.format(base_url,(self.current_page-1))
		page_list.append(prev_page)

		for p in range(bf, af + 1):
			if p == self.current_page:
				temp = '<a class="active" href="{}{}">{}</a>'.format(base_url, p, p)
			else:
				temp = '<a href="{}{}">{}</a>'.format(base_url, p, p)
			page_list.append(temp)

		# 下一页  --即当前页加1（注意当前页为总页数时，需判断）
		if self.current_page >= self.all_page:
			next_page = '<a href="javascript:void(0);">下一页</a>'
		else:
			next_page = '<a href="{}{}">下一页</a>'.format(base_url, (self.current_page + 1))
		page_list.append(next_page)

		# 尾页
		last_page = '<a href="{}{}">尾页</a>'.format(base_url, self.all_page)
		page_list.append(last_page)

		# 输入跳转
		jump_input = '<input type="text" /><a onclick="jump({},this);">GO</a>'.format(base_url)
		jump_script = """
			<script>
				function jump(baseUrl,ths) {
					var val = ths.previousElementSibling.value;
					if(val.trim().length>0){
						location.href = baseUrl + val;
					};
				};
			</script>
		"""
		# previousElementSibling  --获取上一个兄弟的元素节点
		page_list.append(jump_input)
		page_list.append(jump_script)

		return ''.join(page_list)
